import { ref,toRaw } from "vue"
import { ElMessage } from 'element-plus'
import { getIncomeFlowList,getBalanceAcctIdList } from '@/utils/api'
import { addZero } from "@/utils/func";
import { baseurl,incomeTypeList } from "@/utils/constant";
import { useTableStore } from '@/stores/useTableStore';
import { type IncomeParamsInterface } from "@/utils/interface"
export default function() {
    const tableStore = useTableStore();
          tableStore.detailType = 2
    // 数据整合
    function dataFormat(params:IncomeParamsInterface){
      // 收支类型
      let obj :any = {...toRaw(params)}
          obj.page = tableStore.pagination.currentPage
          obj.size = tableStore.pagination.pageSize
      // 时间范围
      if(params['date']){
        let date1 = params['date'][0]
        let date2 = params['date'][1]
        obj.startAt = `${date1.getFullYear()}-${addZero(2,date1.getMonth()+1)}-${addZero(2,date1.getDate())}`;
        obj.endAt   = `${date2.getFullYear()}-${addZero(2,date2.getMonth()+1)}-${addZero(2,date2.getDate())}`;
      }
      delete obj.date
      // 添加全选删除参数
      if(obj.balanceAcctId == '-1'){
            delete obj.balanceAcctId
      }
      console.log("搜索数据条件:",obj);
      return obj
    }
    function getTableIncomeList(){  
        tableStore.tableLoading = true
        let obj = dataFormat(tableStore.formIncome)
        getIncomeFlowList(obj).then(res=>{
          if(res.data.code == 200){
              // 转换数据
              res.data.data[0]['yztAcctDepositList'].map((item:any)=>{
                item.tradeId = item.trade_id
                item.startTime = item.recorded_at
              })
              tableStore.pagination.total= res.data.data[0]['total']
              tableStore.submitLoading   = false
              tableStore.tableLoading    = false
              tableStore.tableUpdateTime = res.data.data[0]['currentTime']
              tableStore.tableIncomeList = res.data.data[0]['yztAcctDepositList']
              console.log('更新表格数据:',res.data);
          }else{
              ElMessage({
                  message : res.data.msg,
                  type    : 'error',
                  duration: 2 * 1000
              })
              tableStore.tableLoading = false
          }
        }).catch(err=>{
            ElMessage({
                message : err,
                type    : 'error',   
                duration: 2 * 1000         
            })
            tableStore.tableLoading = false
        })
    }
    // 获取电子账簿列表
    const balanceAcctIdList = ref(<{name:string,id:string}[]>[{name:'全部',id:'-1'}])
    // tableStore.formIncome.balanceAcctId = '-1' // 默认全部
    getBalanceAcctIdList().then(res=>{
        if(res.data.code == 200){
            console.log(res.data)
            balanceAcctIdList.value = [...balanceAcctIdList.value, ...res.data.data]
        }else{
            ElMessage({
                message : res.data.msg,
                type    : 'error',
                duration: 2 * 1000
            })
            tableStore.tableLoading = false
        }
    }).catch(err=>{
        ElMessage({
            message : err,
            type    : 'error',   
            duration: 2 * 1000         
        })
        tableStore.tableLoading = false
    })
    // 类型列表中提取名称
    function isIncomeType(id:number){
        let obj = incomeTypeList.find(item=>{
            return item.id == id;
        })
        return (<{id:number,label:string}>obj).label
    }
    // 下载全部数据
    function downloadAllData(){
        // 搜索条件发送到接口
        let obj = dataFormat(tableStore.formIncome)
        console.log('下载全部数据:',obj);
        let balanceAcctId = obj.balanceAcctId;
        let tradeType     = obj.tradeType;
        let startAt       = obj.startAt;
        let endAt         = obj.endAt;
        // let createBy      = obj.create_by;
        // let shopId        = obj.shop_id;
        let url           = `${baseurl}/withdraw/getIncomeDownLoad?type=0&`;
        // 拼接参数
            url += balanceAcctId ? `balanceAcctId=${balanceAcctId}&` : '';
            url += tradeType ? `tradeType=${tradeType}&` : '';
            url += startAt ? `startAt=${startAt}&` : '';
            url += endAt ? `endAt=${endAt}&` : '';
            // url += createBy ? `createBy=${createBy}&` : '';
            // url += shopId ? `shopId=${shopId}&` : '';
        if(url.endsWith('&')){
          url = url.slice(0,-1)
        }
        let a = document.createElement('a');
            a.href   = url;
            a.target = "_blank";
            a.click();
            a.remove()
    }
    return {
        getTableIncomeList,
        isIncomeType,
        downloadAllData,
        balanceAcctIdList
    }
}